//
//  BuildingMgmtViewController.m
//  FMS
//
//  Created by Steven on 10/12/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "BuildingMgmtViewController.h"
#import "AddNewItemViewController.h"
#import "DetailedItemViewController.h"
#import "MaintenanceMgmtViewController.h"
#import "MaintenanceTypeViewController.h"
#import "MaintenanceDetailedViewController.h"
#import "ListScheduleViewController.h"
#import "ScheduleInspectionViewController.h"
#import "DocumentLinkViewController.h"

@interface BuildingMgmtViewController ()

@end

@implementation BuildingMgmtViewController
@synthesize parent;
@synthesize serviceType;
@synthesize maintenanceType;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil itemType:(int)_itemType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        itemType = _itemType;
        buildingId = @"";
        serviceId  = @"";
        campId     = @"";
    }
    return self;
}

- (IBAction)addNewItem:(id)sender {
#ifndef vDEBUG
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *buildingPermissionDict;
    
    if (itemType == Building_Type)
        buildingPermissionDict= [userDefaults objectForKey:BUILDING_PERMISSION];
    else
        buildingPermissionDict= [userDefaults objectForKey:FACILITY_PERMISSION];
    
    //Get permission about this tab
    //if has Edit permission is also has Add permission
    NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"detailsInfo"];
    BOOL isAdd = [[permissionDict objectForKey:@"add"] boolValue];
    if (!isAdd) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
#endif
    
    AddNewItemViewController *controller = [[AddNewItemViewController alloc] initWithNibName:@"AddNewItemViewController" bundle:nil itemType:itemType parent:self];
    [self.navigationController pushViewController:controller animated:YES];
}

- (IBAction) backPreviousView:(id)sender {
    if ([parent isKindOfClass:[MaintenanceMgmtViewController class]] || [parent isKindOfClass:[ListScheduleViewController class]] || [parent isKindOfClass:[DetailedItemViewController class]] || [parent isKindOfClass:[DocumentLinkViewController class]])
        [self.navigationController popViewControllerAnimated:NO];
    else
        [self dismissModalViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    
    [_leftBackground setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"grayPattern.png"]]];
    
    // Do any additional setup after loading the view from its nib.
//    self.mySearchBar.myBackgroundColor = _leftBackground.backgroundColor;
    self.mySearchBar.fromView = 1; //Building Mgmt
    self.mySearchBar.tintColor = [UIColor blueColor];
    
    mainArray = [NSMutableArray arrayWithCapacity:1];
    searchArray = [NSMutableArray arrayWithCapacity:1];
    
    _mainTableView.layer.borderColor = APPLE_BLUE_COLOR.CGColor;
    _mainTableView.layer.borderWidth = 1;
    
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    if (self.btnCategoryProgram) {
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
        imgView.frame = CGRectMake(220, 11, 13, 8);
        

        [self.btnCategoryProgram addSubview:imgView];
        
        //set color for filter button
        [self.btnCategoryProgram setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.btnCategoryProgram setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [self.btnCategoryProgram setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
    }
    
    if (self.btnWorkType) {
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
        imgView.frame = CGRectMake(220, 11, 13, 8);
        
        
        [self.btnWorkType addSubview:imgView];
        
        //set color for filter button
        [self.btnWorkType setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.btnWorkType setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [self.btnWorkType setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
    }
    
    //add drop down button for filter button
    for (int i=0;i < 9;i++) {
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
        imgView.frame = CGRectMake(220, 11, 13, 8);
        
        UIButton *btn = (UIButton*)[self.view viewWithTag:100+i];
        [btn addSubview:imgView];
        
        //set color for filter button
        [btn setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [btn setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
    }
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iconDropDown.png"]];
    imgView.frame = CGRectMake(220, 11, 13, 8);
    
    [_btnSelectLocation addSubview:imgView];
    
    //set color for filter button
    [_btnSelectLocation setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_btnSelectLocation setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_btnSelectLocation setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateHighlighted];
    
    //init filter array value
    if (itemType == Building_Type) {
        _lbChooseItem.text = [dictLanguage objectForKey:@"building-mgmt.list-room.select-item"];
        
        filterDictValue = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",0],@"service",[NSString stringWithFormat:@"%d",0],@"camp",[NSString stringWithFormat:@"%d",0],@"unit",[NSString stringWithFormat:@"%d",0],@"building",[NSString stringWithFormat:@"%d",0],@"floor",[NSString stringWithFormat:@"%d",0],@"room", nil];
    }
    else {
        _lbChooseItem.text = [dictLanguage objectForKey:@"facility-mgmt.list-equipment.select-item"];
        
        filterDictValue = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",0],@"service",[NSString stringWithFormat:@"%d",0],@"camp",[NSString stringWithFormat:@"%d",0],@"unit",[NSString stringWithFormat:@"%d",0],@"building",[NSString stringWithFormat:@"%d",0],@"floor",[NSString stringWithFormat:@"%d",0],@"room",[NSString stringWithFormat:@"%d",0],@"system",[NSString stringWithFormat:@"%d",0],@"description", nil];
    }
    
    //check condition if select Facility Mgmt
    [self switchItemType];
    
    //check if controller is loaded by Maintenance Mgmt controller, hide Add New button
    if ([parent isKindOfClass:[ListScheduleViewController class]]) {
        itemType = Building_Type;
        [self.btnWorkType setTitle:[dictLanguage objectForKey:@"schedule.title-select-work-type"] forState:UIControlStateNormal];
        [self.btnCategoryProgram setTitle:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"] forState:UIControlStateNormal];
        self.viewFilterItem.frame = CGRectMake(self.viewFilterItem.frame.origin.x, 149, self.viewFilterItem.frame.size.width, self.viewFilterItem.frame.size.height);
        [filterDictValue removeObjectForKey:@"system"];
        [filterDictValue removeObjectForKey:@"description"];
        
        [self.btnBack setBackgroundImage:[UIImage imageNamed:@"btnBack.png"] forState:UIControlStateNormal];
    }
    else {
        self.btnWorkType.hidden = self.btnCategoryProgram.hidden = YES;
        
        _viewFilterItem.center = CGPointMake(_viewFilterItem.center.x, _viewFilterItem.center.y-38);
    }
    if ([parent isKindOfClass:[MaintenanceMgmtViewController class]] || [parent isKindOfClass:[ListScheduleViewController class]] || [parent isKindOfClass:[DocumentLinkViewController class]]) {
        _btnAddNew.hidden = YES;
        
        //display Select Item Type button and arrange position of filter buttons.
        _btnSelectItemType.hidden = NO;
        
        _btnSelectItemType.center = _btnSelectService.center;
        _btnSelectService.center  = CGPointMake(_btnSelectItemType.center.x, _btnSelectItemType.center.y+45);
        _btnSelectCamp.center   = CGPointMake(_btnSelectService.center.x, _btnSelectService.center.y+45);
        _btnSelectUnit.center   = CGPointMake(_btnSelectService.center.x, _btnSelectCamp.center.y+45);
        _btnSelectBuilding.center   = CGPointMake(_btnSelectService.center.x, _btnSelectUnit.center.y+45);
        _btnSelectFloor.center   = CGPointMake(_btnSelectService.center.x, _btnSelectBuilding.center.y+45);
        _btnSelectRoom.center   = CGPointMake(_btnSelectService.center.x, _btnSelectFloor.center.y+45);
    }
    
    //check iOS 7 view
    if (SYSTEM_VERSION_LESS_THAN(@"7.0"));
    else {
        self.mainTableView.frame = CGRectMake(self.mainTableView.frame.origin.x, self.mainTableView.frame.origin.y, self.mainTableView.frame.size.width, self.mainTableView.frame.size.height-54);
    }
    
    //block touch event first
    [self setButtonFilterEnable:NO];
    
    myActivityView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(650, 400, 30, 30)];
    myActivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    myActivityView.hidesWhenStopped = YES;
    [myActivityView startAnimating];
    [self.view addSubview:myActivityView];
    
    //create a view to prevent touch when init data
    btnCurtain = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCurtain.frame = CGRectMake(0, 0, 1024, 768);
    [btnCurtain setBackgroundColor:[UIColor whiteColor]];
    btnCurtain.alpha = 0.5;
    [btnCurtain addTarget:self action:@selector(doNothing) forControlEvents:UIControlEventTouchUpInside];
    [ApplicationDelegate.tabBarController.view addSubview:btnCurtain];
    
    //hide search bar if role = contractor
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
    }
    else {
        _mySearchBar.hidden = YES;
        
        _lbShowItem.center = CGPointMake(_lbShowItem.center.x, _lbShowItem.center.y-44);
        _btnCategoryProgram.center = CGPointMake(_btnCategoryProgram.center.x, _btnCategoryProgram.center.y-44);
        _btnWorkType.center = CGPointMake(_btnWorkType.center.x, _btnWorkType.center.y-44);
        _viewFilterItem.center = CGPointMake(_viewFilterItem.center.x, _viewFilterItem.center.y-44);
    }
}

- (void) doNothing {

}

- (void) setButtonFilterEnable:(BOOL)enable {
    [_btnSelectService setEnabled:enable];
    [_btnSelectBuilding setEnabled:enable];
    [_btnSelectCamp setEnabled:enable];
    [_btnSelectFloor setEnabled:enable];
    [_btnSelectRoom setEnabled:enable];
    [_btnSelectDescription setEnabled:enable];
    [_btnSelectSystem setEnabled:enable];
    [_btnSelectUnit setEnabled:enable];
}
- (void) switchItemType {
    if (itemType == Facility_Type) {
        _lbItemID.hidden = NO;
        _lbItemID.frame = CGRectMake(31, 11, _lbItemID.frame.size.width, _lbItemID.frame.size.height);
        _lbRoom.frame = CGRectMake(_lbItemID.frame.origin.x+_lbItemID.frame.size.width, 11, _lbRoom.frame.size.width, _lbRoom.frame.size.height);
        _lbFloor.frame = CGRectMake(_lbRoom.frame.origin.x+_lbRoom.frame.size.width, 11, _lbFloor.frame.size.width, _lbFloor.frame.size.height);
        _lbBuilding.frame = CGRectMake(_lbFloor.frame.origin.x+_lbFloor.frame.size.width, 11, _lbBuilding.frame.size.width, _lbBuilding.frame.size.height);
        
        _lbChooseItem.text = [dictLanguage objectForKey:@"facility-mgmt.list-equipment.select-item"];
        _lbMainTitle.text = [dictLanguage objectForKey:@"facility-mgmt.main-title"];
        _btnSelectSystem.hidden = _btnSelectDescription.hidden = NO;
        
        [_btnSelectItemType setTitle:[dictLanguage objectForKey:@"schedule.title-equipment"] forState:UIControlStateNormal];
        
//        [self performSelectorInBackground:@selector(listEquipment) withObject:nil];
        [self performSelector:@selector(listEquipment) withObject:nil afterDelay:0.5];
    }
    else {
        _lbItemID.hidden = YES;
        _lbItemID.frame = CGRectMake(31, 11, _lbItemID.frame.size.width, _lbItemID.frame.size.height);
        
        if ([parent isKindOfClass:[MaintenanceMgmtViewController class]] || [parent isKindOfClass:[DocumentLinkViewController class]]) {
            _lbRoom.frame = CGRectMake(_lbItemID.frame.origin.x, 11, _lbRoom.frame.size.width, _lbRoom.frame.size.height);
            _lbFloor.frame = CGRectMake(240, 11, _lbFloor.frame.size.width, _lbFloor.frame.size.height);
            _lbBuilding.frame = CGRectMake(490, 11, _lbBuilding.frame.size.width, _lbBuilding.frame.size.height);
        }
        
        _lbChooseItem.text = [dictLanguage objectForKey:@"building-mgmt.list-room.select-item"];
        _lbMainTitle.text = [dictLanguage objectForKey:@"building-mgmt.main-title"];
        _btnSelectSystem.hidden = _btnSelectDescription.hidden = _btnSelectRoom.hidden = YES;
        
        [_btnSelectItemType setTitle:[dictLanguage objectForKey:@"schedule.title-building"] forState:UIControlStateNormal];
        
//        [self performSelectorInBackground:@selector(listRoom) withObject:nil];
        [self performSelector:@selector(listRoom) withObject:nil afterDelay:0.5];
    }
}

- (void) listRoom {
    isSearching = NO;
    [mainArray removeAllObjects];
    [self.mainTableView reloadData];
    [myActivityView startAnimating];
    
    currentRecordIndex = 0;
    
    [self setButtonFilterEnable:NO];
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listRoom", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listRoomByFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listRoomByFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }

            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
//                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
//                }
//                else
//                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                [self setButtonFilterEnable:YES];
                [myActivityView stopAnimating];
                
                [btnCurtain removeFromSuperview];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreRoom {
    [self setButtonFilterEnable:NO];
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreRoom", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listRoomByFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listRoomByFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
//                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
//                }
//                else
//                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    @try {
                        [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                    }
                    @catch (NSException *e) {
                        NSLog(@"%@",e);
                    }
                }
                
                isLock = NO;
                
                [self setButtonFilterEnable:YES];
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listRoomByKey:(NSString*)_searchKey {
    isSearching = YES;
    [mainArray removeAllObjects];
    [self.mainTableView reloadData];
    [myActivityView startAnimating];
    currentRecordIndex = 0;
    
    [self setButtonFilterEnable:NO];
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listRoomByKey:_searchKey andFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listRoomByKey:_searchKey andFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                [self setButtonFilterEnable:YES];
                [myActivityView stopAnimating];
                [btnCurtain removeFromSuperview];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreRoomByKey:(NSString*)_searchKey {
    [self setButtonFilterEnable:NO];
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listRoomByKey:_searchKey andFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listRoomByKey:_searchKey andFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    @try {
                        [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                    }
                    @catch (NSException *e) {
                        NSLog(@"%@",e);
                    }
                }
                
                isLock = NO;
                
                [self setButtonFilterEnable:YES];
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listEquipment {
    isSearching = NO;
    [mainArray removeAllObjects];
    [self.mainTableView reloadData];
    [myActivityView startAnimating];
    currentRecordIndex = 0;
    
    [self setButtonFilterEnable:NO];
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listEquipment", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listEquipmentByFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listEquipmentByFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                @try {
                    NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                    [mainArray addObject:dict];
                }
                @catch (NSException *e) {
                    NSLog(@"%@",e);
                }
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                [self setButtonFilterEnable:YES];
                
                [myActivityView stopAnimating];
                [btnCurtain removeFromSuperview];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreEquipment {
    [self setButtonFilterEnable:NO];
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreEquipment", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listEquipmentByFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listEquipmentByFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    @try {
                        [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                    }
                    @catch (NSException *e) {
                        NSLog(@"%@",e);
                    }
                }
                
                isLock = NO;
                
                [self setButtonFilterEnable:YES];
                
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listEquipmentByKey:(NSString*)_searchKey {
    isSearching = YES;
    [mainArray removeAllObjects];
    [self.mainTableView reloadData];
    [myActivityView startAnimating];
    currentRecordIndex = 0;
    
    [self setButtonFilterEnable:NO];
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listEquipmentByKey:_searchKey andFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listEquipmentByKey:_searchKey andFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                [self setButtonFilterEnable:YES];
                
                [myActivityView stopAnimating];
                [btnCurtain removeFromSuperview];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreEquipmentByKey:(NSString*)_searchKey {
    [self setButtonFilterEnable:NO];
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray;
            //check permission to list room
            //MA và Owner view all room, Contractor chỉ view được những room assign cho nó
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
            if ([role isEqualToString:@"ma"] || [role isEqualToString:@"owner"] || [role isEqualToString:@"admin"]) {
                tmpArray = [CouchBaseLiteLib listEquipmentByKey:_searchKey andFilter:filterDictValue from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            else {
                NSString *contractorId = [userDefaults objectForKey:ACCOUNT_ID];
                tmpArray = [CouchBaseLiteLib listEquipmentByKey:_searchKey andFilter:filterDictValue contractor:contractorId from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            }
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [tmpArray objectAtIndex:i];
                [mainArray addObject:dict];
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                if (isLoadMore) {
//                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    @try {
                        [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                    }
                    @catch (NSException *e) {
                        NSLog(@"%@",e);
                    }
                }
                
                isLock = NO;
                
                [self setButtonFilterEnable:YES];
                
                [myActivityView stopAnimating];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) reloadAfterUpdate:(NSMutableDictionary*)_dict {
    for (int i=0;i < [mainArray count];i++) {
        NSMutableDictionary *tmpDict = [mainArray objectAtIndex:i];
        NSString *_id = [tmpDict objectForKey:@"_id"];
        
        if ([_id isEqualToString:[_dict objectForKey:@"_id"]]) {
            [mainArray replaceObjectAtIndex:i withObject:_dict];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            NSArray *tmpArray = [NSArray arrayWithObject:indexPath];
            [_mainTableView reloadRowsAtIndexPaths:tmpArray withRowAnimation:UITableViewRowAnimationAutomatic];
            
            break;
        }
    }
}

- (IBAction) selectFilter:(UIButton*)sender {
    int filterType = sender.tag;
    
    //init controller to filter value
    FilterViewController *controller;
    if ([parent isKindOfClass:[ListScheduleViewController class]] && filterType == filter_item_type) {
        controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_work_type];
    }
    else
        controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filterType];
    controller.delegate = self;
    controller.filterValueDict = filterDictValue;
    controller.itemType = itemType;
    
    switch (filterType) {
        case filter_floor:
            controller.buildingId = buildingId;
            break;
        case filter_service:
            controller.serviceId = serviceId;
            break;
        case filter_camp:
            controller.serviceId = serviceId;
            controller.campId = campId;
            break;
        case filter_unit:
            controller.serviceId = serviceId;
            controller.campId = campId;
            break;
        case filter_building:
        case filter_location:
            controller.unitId = unitId;
            break;
        case filter_description:
            controller.systemName = _btnSelectSystem.titleLabel.text;
            break;
        default:
            break;
    }
    
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:sender.frame inView:[sender superview]permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)selectCategoryProgram:(id)sender {
    
    UIButton *btnSender = (UIButton *)sender;
    
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_category];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)selectWorkType:(id)sender {
    
    UIButton *btnSender = (UIButton *)sender;
    
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_maintenance];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

}

#pragma mark - FilterView delegate

- (void) didSelectFilter:(NSMutableDictionary *)filterDict {
    [popoverController dismissPopoverAnimated:YES];
    int filterType = [[filterDict objectForKey:@"filterType"] intValue];
    
    if (filterType == filter_category) {
        
        [self.btnCategoryProgram setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
        
        if ([[filterDict objectForKey:@"index"] intValue]== Inspection) {
            [filterDictValue removeObjectForKey:@"itemType"];
            
            self.btnWorkType.hidden = YES;
//            self.viewFilterItem.frame = CGRectMake(self.viewFilterItem.frame.origin.x, 149, self.viewFilterItem.frame.size.width, self.viewFilterItem.frame.size.height);
            self.viewFilterItem.frame = CGRectMake(_viewFilterItem.frame.origin.x, _btnWorkType.frame.origin.y, _viewFilterItem.frame.size.width, _viewFilterItem.frame.size.height);
        }
        else{
            self.btnWorkType.hidden = NO;
//            self.viewFilterItem.frame = CGRectMake(self.viewFilterItem.frame.origin.x, 205, self.viewFilterItem.frame.size.width, self.viewFilterItem.frame.size.height);
            self.viewFilterItem.frame = CGRectMake(_viewFilterItem.frame.origin.x, _btnWorkType.frame.origin.y+44, _viewFilterItem.frame.size.width, _viewFilterItem.frame.size.height);
        }
    }
    else if(filterType == filter_maintenance){
        [self.btnWorkType setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
        maintenanceType = [[filterDict objectForKey:@"index"] intValue];
    }
//    else if (filterType == filter_work_type) {
//        [self.btnSelectItemType setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
//    }
    else{
        if (filterType == filter_work_type) {
            [self.btnSelectItemType setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
            itemType = [[filterDict objectForKey:@"index"] intValue];
        }
        else{
            UIButton *btnFilter = (UIButton*)[self.view viewWithTag:filterType];
            [btnFilter setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
        }
        
        NSString *filterIndex = [filterDict objectForKey:@"index"];
        
        //set filter array value
        NSString *filterKeyName = @"";
        
        //filterKeyName is the key name in database. Eg: Room is service,room,unit...
        
        switch (filterType) {
            case filter_service:
                serviceId = [filterDict objectForKey:@"index"];
                filterKeyName = @"service";
                
                //if select service, reset camp and unit
                campId = @"0";
                unitId = @"0";
                buildingId = @"0";
                floorId = @"0";
                
                [_btnSelectCamp setTitle:[dictLanguage objectForKey:@"filter.select-camp"] forState:UIControlStateNormal];
                [_btnSelectUnit setTitle:[dictLanguage objectForKey:@"filter.select-unit"] forState:UIControlStateNormal];
                [_btnSelectBuilding setTitle:[dictLanguage objectForKey:@"filter.select-building"] forState:UIControlStateNormal];
                [_btnSelectFloor setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                [_btnSelectRoom setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                
                [filterDictValue setObject:@"0" forKey:@"camp"];
                [filterDictValue setObject:@"0" forKey:@"building"];
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
                [filterDictValue setObject:@"0" forKey:@"unit"];
                
                _btnSelectLocation.hidden = YES;
                _btnSelectFloor.hidden = _btnSelectRoom.hidden = NO;
                _btnSelectSystem.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+45);
                _btnSelectDescription.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+90);
                
                break;
            case filter_camp:
                campId = [filterDict objectForKey:@"index"];
                filterKeyName = @"camp";
                
                unitId = @"0";
                buildingId = @"0";
                floorId = @"0";
                
                //reset unit
                [_btnSelectUnit setTitle:[dictLanguage objectForKey:@"filter.select-unit"] forState:UIControlStateNormal];
                [_btnSelectBuilding setTitle:[dictLanguage objectForKey:@"filter.select-building"] forState:UIControlStateNormal];
                [_btnSelectFloor setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                [_btnSelectRoom setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                
                [filterDictValue setObject:@"0" forKey:@"building"];
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
                [filterDictValue setObject:@"0" forKey:@"unit"];
                
                _btnSelectLocation.hidden = YES;
                _btnSelectFloor.hidden = _btnSelectRoom.hidden = NO;
                _btnSelectSystem.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+45);
                _btnSelectDescription.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+90);
                
                break;
            case filter_unit:
                filterKeyName = @"unit";
                unitId = [filterDict objectForKey:@"index"];
                
                buildingId = @"0";
                floorId = @"0";
                
                //reset unit
                [_btnSelectBuilding setTitle:[dictLanguage objectForKey:@"filter.select-building"] forState:UIControlStateNormal];
                [_btnSelectFloor setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                [_btnSelectRoom setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                
                [filterDictValue setObject:@"0" forKey:@"building"];
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
                
                _btnSelectLocation.hidden = YES;
                _btnSelectFloor.hidden = _btnSelectRoom.hidden = NO;
                _btnSelectSystem.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+45);
                _btnSelectDescription.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+90);
                
                break;
            case filter_building:
                buildingId = [filterDict objectForKey:@"index"];
                filterKeyName = @"building";
                
                floorId = @"0";
                
                //reset unit
                [_btnSelectFloor setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                [_btnSelectRoom setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
                
                if (itemType != Building_Type) {
                    if ([[filterDict objectForKey:@"filterName"] isEqualToString:[dictLanguage objectForKey:@"filter.select-building.other"]]) {
                        _btnSelectFloor.hidden = _btnSelectRoom.hidden = YES;
                        _btnSelectLocation.hidden = NO;
                        _btnSelectDescription.center = _btnSelectSystem.center;
                        _btnSelectSystem.center = _btnSelectRoom.center;
                        
                        //get list location and set the first row for btnSelectLocation
                        NSMutableArray *otherBuildingArray = [CouchBaseLiteLib listOtherBuildingByUnit:unitId from:0 numberRow:NUMBER_ROW_PAGE];
                        if ([otherBuildingArray count] > 0) {
                            NSMutableDictionary *dict = [otherBuildingArray objectAtIndex:0];
                            filterDict = [dict mutableCopy];
                            
                            buildingId = [filterDict objectForKey:@"index"];
                            filterKeyName = @"building";
                            
                            [_btnSelectLocation setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
                        }
                    }
                    else {
                        _btnSelectLocation.hidden = YES;
                        _btnSelectFloor.hidden = _btnSelectRoom.hidden = NO;
                        _btnSelectSystem.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+45);
                        _btnSelectDescription.center = CGPointMake(_btnSelectRoom.center.x, _btnSelectRoom.center.y+90);
                    }
                }
                break;
            case filter_location:
                buildingId = [filterDict objectForKey:@"index"];
                filterKeyName = @"building";
                
                floorId = @"0";
                
                //reset unit
                [_btnSelectFloor setTitle:[dictLanguage objectForKey:@"filter.select-floor"] forState:UIControlStateNormal];
                [_btnSelectRoom setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
                break;
            case filter_floor:
                filterKeyName = @"floor";
                
                floorId = [filterDict objectForKey:@"index"];
                
                [_btnSelectRoom setTitle:[dictLanguage objectForKey:@"filter.select-room"] forState:UIControlStateNormal];
                
                [filterDictValue setObject:@"0" forKey:@"room"];
                
                break;
            case filter_room:
                filterKeyName = @"room";
                break;
            case filter_system:
                filterKeyName = @"system";
                
                //reset description
                [_btnSelectDescription setTitle:[dictLanguage objectForKey:@"filter.select-description"] forState:UIControlStateNormal];
                [filterDictValue setObject:@"0" forKey:@"description"];
                break;
            case filter_description:
                filterKeyName = @"description";
                break;
            default:
                break;
        }
        
        if (filterType == filter_item_type || filterType == filter_work_type) {
            itemType = [[filterDict objectForKey:@"index"] intValue];
            
            //reset description, system
            [filterDictValue setObject:@"0" forKey:@"description"];
            [_btnSelectDescription setTitle:[dictLanguage objectForKey:@"filter.select-description"] forState:UIControlStateNormal];
            
            [filterDictValue setObject:@"0" forKey:@"system"];
            [_btnSelectSystem setTitle:[dictLanguage objectForKey:@"filter.select-system"] forState:UIControlStateNormal];
        }
        else {
            //if select all, we set 0 to this key
            if ([filterIndex isEqualToString:@"0"]) {
                [filterDictValue setObject:@"0" forKey:filterKeyName];
            }
            else
                [filterDictValue setObject:[filterDict objectForKey:@"filterName"] forKey:filterKeyName];
            
            /*
            //reset after select another
            if ([serviceId isEqualToString:@"0"]) {
                [filterDictValue setObject:@"0" forKey:@"camp"];
                [filterDictValue setObject:@"0" forKey:@"unit"];
                [filterDictValue setObject:@"0" forKey:@"building"];
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
            }
            else if ([campId isEqualToString:@"0"]){
                [filterDictValue setObject:@"0" forKey:@"unit"];
                [filterDictValue setObject:@"0" forKey:@"building"];
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
            }
            else if ([unitId isEqualToString:@"0"]) {
                [filterDictValue setObject:@"0" forKey:@"building"];
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
            }
            else if ([buildingId isEqualToString:@"0"]) {
                [filterDictValue setObject:@"0" forKey:@"floor"];
                [filterDictValue setObject:@"0" forKey:@"room"];
            }
            else if ([floorId isEqualToString:@"0"]) {
                [filterDictValue setObject:@"0" forKey:@"room"];
            }
            
            if ([systemId isEqualToString:@"0"]) {
                [filterDictValue setObject:@"0" forKey:@"description"];
            }
            */
        }
        //change action and view with new itemType
        if (itemType == Building_Type) {
            _btnSelectSystem.hidden = _btnSelectDescription.hidden = YES;
            [self switchItemType];
        }
        else {
            _btnSelectSystem.hidden = _btnSelectDescription.hidden = NO;
            [self switchItemType];
        }
        if (filterType == filter_work_type) {
            [self.btnSelectItemType setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (isSearching && [mainArray count] == 0)
        return [searchArray count];
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    @try {
        
        NSMutableDictionary *dict;
        if (isSearching && [mainArray count] == 0)
            dict = [searchArray objectAtIndex:indexPath.row];
        else
            dict = [mainArray objectAtIndex:indexPath.row];
        //    NSMutableArray *itemData  = [dict objectForKey:@"itemData"];
        
        UILabel *lbRoom = [[UILabel alloc] initWithFrame:CGRectMake(30, 10, 180, 21)];
        lbRoom.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:lbRoom];
        
        UILabel *lbFloor = [[UILabel alloc] initWithFrame:CGRectMake(240, 10, 130, 21)];
        lbFloor.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:lbFloor];
        
        UILabel *lbBuilding = [[UILabel alloc] initWithFrame:CGRectMake(490, 10, 150, 21)];
        lbBuilding.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:lbBuilding];
        
        UILabel *lbItemID;
        if (itemType == Facility_Type) {
            lbItemID = [[UILabel alloc] initWithFrame:CGRectMake(30, 10, 210, 21)];
            lbItemID.backgroundColor = [UIColor clearColor];
            lbItemID.text = [dict objectForKey:@"itemId"];
            [cell.contentView addSubview:lbItemID];
            
            //arrange the position of these label
            lbRoom.frame = CGRectMake(lbItemID.frame.origin.x+lbItemID.frame.size.width, 10, lbRoom.frame.size.width, lbRoom.frame.size.height);
            lbFloor.frame = CGRectMake(lbRoom.frame.origin.x+lbRoom.frame.size.width, 10, lbFloor.frame.size.width, lbFloor.frame.size.height);
            lbBuilding.frame = CGRectMake(lbFloor.frame.origin.x+lbFloor.frame.size.width, 10, lbBuilding.frame.size.width, lbBuilding.frame.size.height);
            
            if ([[dict objectForKey:@"room"] isEqualToString:@"0"])
                lbRoom.text     = @"";
            else
                lbRoom.text     = [dict objectForKey:@"room"];
        }
        else {
            if ([[dict objectForKey:@"item_name"] isEqualToString:@"0"])
                lbRoom.text     = @"";
            else
                lbRoom.text     = [dict objectForKey:@"item_name"];
        }
        
        if ([[dict objectForKey:@"floor"] isEqualToString:@"0"])
            lbFloor.text = @"";
        else
            lbFloor.text    = [dict objectForKey:@"floor"];
        lbBuilding.text = [dict objectForKey:@"building"];
        lbItemID.text   = [dict objectForKey:@"item_name"];
        
    }
    @catch (NSException *e) {
        NSLog(@"%@",e);
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *itemDict;
    if (isSearching && [mainArray count] == 0)
        itemDict = [searchArray objectAtIndex:indexPath.row];
    else
        itemDict = [mainArray objectAtIndex:indexPath.row];
    
    if ([parent isKindOfClass:[MaintenanceMgmtViewController class]]) {
        //if serviceType = Maintenance, display tableview to list maintenance type
        if (serviceType == Maintenance){
            MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
            controller.itemDetailedDict = itemDict;
            controller.itemType = itemType;
            UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
            navController.modalPresentationStyle = UIModalPresentationPageSheet;
            [self presentModalViewController:navController animated:YES];
            
            if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
        }
        else {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *userId = [userDefaults objectForKey:ACCOUNT_ID];
            //create temporary inspection
            NSMutableDictionary *inputInspectionDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:InspectionDoc,@"Table",userId,@"userId", nil];
            NSError *error;
            if ([[CouchBaseLiteLib sharedCouchBaseLite] createDocument:inputInspectionDict error:&error]) {
                MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Inspection];
                controller.itemDetailDict = itemDict;
                controller.itemType = itemType;
                controller.inputInspectionDict = inputInspectionDict;
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
    }
    else if([parent isKindOfClass:[ListScheduleViewController class]]){
        //check select worktype
        if(![[self.btnCategoryProgram titleForState:UIControlStateNormal] isEqualToString:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"]] && ([self.btnWorkType titleForState:UIControlStateNormal] == nil ||[[self.btnWorkType titleForState:UIControlStateNormal] isEqualToString:[dictLanguage objectForKey:@"schedule.title-select-work-type"]])){
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"schedule.title-required-select-work-type"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        NSDate *today = [NSDate date];
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        NSString *todayStr = [dateFormatter stringFromDate:today];
        NSString *todayStr = [NSDate stringFormatDateFullFromDate:today];
        
        NSMutableDictionary *dictSchedule = [NSMutableDictionary dictionaryWithObjectsAndKeys:[self.btnCategoryProgram titleForState:UIControlStateNormal],@"scheduleCategory",[itemDict objectForKey:@"service"],@"service",[itemDict objectForKey:@"camp"],@"camp",[itemDict objectForKey:@"unit"],@"unit",[itemDict objectForKey:@"building"],@"building",[itemDict objectForKey:@"floor"],@"floor",@"",@"startDate",todayStr,@"lastUpdate",@"",@"reMark",[self.btnWorkType titleForState:UIControlStateNormal],@"maintenanceType",[NSNumber numberWithInt:maintenanceType],@"maintenanceTypeId",[NSNumber numberWithInt:0],@"categoryTypeId",[itemDict objectForKey:@"_id"],@"itemId",nil];
        if (itemType == Facility_Type)
            [dictSchedule setObject:[itemDict objectForKey:@"room"] forKey:@"room"];
        else
            [dictSchedule setObject:[itemDict objectForKey:@"item_name"] forKey:@"room"];
        if (itemType == Building_Type) {

            [dictSchedule setObject:[NSNumber numberWithInt:Building_Type] forKey:@"itemType"];
        }
        else
            [dictSchedule setObject:[NSNumber numberWithInt:Facility_Type] forKey:@"itemType"];
        if ([[dictSchedule objectForKey:@"scheduleCategory"] isEqualToString:[dictLanguage objectForKey:@"maintenance-mgmt.service-type.inspection"]]) {
            [dictSchedule setObject:[NSNumber numberWithInt:Inspection] forKey:@"categoryId"];
            if (itemType != Facility_Type)
                [dictSchedule setObject:[NSNumber numberWithInt:Schedule_AIP_Mgmt_Type] forKey:SCHEDULE_MGMT_TYPE];
        }
        else
        {
            [dictSchedule setObject:[NSNumber numberWithInt:Maintenance] forKey:@"categoryId"];
            
            if (itemType == Facility_Type)
                [dictSchedule setObject:[NSNumber numberWithInt:Schedule_AMP_Mgmt_Type] forKey:SCHEDULE_MGMT_TYPE];
        }
        
        
        //push to Schedule view to set schedule again
        ScheduleInspectionViewController *controller = [[ScheduleInspectionViewController alloc] initWithNibName:@"ScheduleInspectionViewController" bundle:[NSBundle mainBundle] schedule:dictSchedule];
        controller.delegate = self;
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if ([parent isKindOfClass:[DetailedItemViewController class]]) {
        //if serviceType = Maintenance, display tableview to list maintenance type
        if (serviceType == Maintenance){
            MaintenanceTypeViewController *controller = [[MaintenanceTypeViewController alloc] initWithNibName:@"MaintenanceTypeViewController" bundle:nil serviceType:Maintenance parent:self];
            controller.itemDetailedDict = itemDict;
            controller.itemType = itemType;
            UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
            navController.modalPresentationStyle = UIModalPresentationPageSheet;
            [self presentModalViewController:navController animated:YES];
            
            if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
                navController.view.superview.frame = CGRectMake(300, 100, 400, 400);
        }
        else {
            MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Inspection];
            controller.itemDetailDict = itemDict;
            controller.itemType = itemType;
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
    else if ([parent isKindOfClass:[DocumentLinkViewController class]]) {
        if ([(DocumentLinkViewController*)parent handleAddNewDocumentForItem:itemDict]){
            //duplicate document for this item
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"building-mgmt.detail.document-link.duplicate"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
        }
        else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *buildingPermissionDict = [userDefaults objectForKey:BUILDING_PERMISSION];
        
        //Get permission about this tab
        NSMutableDictionary *permissionDict = [buildingPermissionDict objectForKey:@"detailsInfo"];
        BOOL isAccess = [[permissionDict objectForKey:@"access"] boolValue];
        if (!isAccess) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        
        DetailedItemViewController *controller = [[DetailedItemViewController alloc] initWithNibName:@"DetailedItemViewController" bundle:nil itemType:itemType parent:self];
        controller.itemDetailedDict = itemDict;
        [self.navigationController pushViewController:controller animated:YES];
        
        //use to check and reload data
        [userDefaults setObject:[NSNumber numberWithInt:BuildingMgmt] forKey:SUPER_PARENT];
    }
}

- (void) confirmSelectMaintenance:(NSMutableDictionary*)_dict itemDetailedDict:(NSMutableDictionary*)_itemDetailedDict {
    //if add new maintenance, set isInspectionFailed = NO
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithBool:NO] forKey:IS_INSPECTION_FAILED];
    
    MaintenanceDetailedViewController *controller = [[MaintenanceDetailedViewController alloc] initWithNibName:@"MaintenanceDetailedViewController" bundle:nil parent:self serviceType:Maintenance];
    controller.itemDetailDict = [_itemDetailedDict mutableCopy];
    [controller.itemDetailDict setObject:[_itemDetailedDict objectForKey:@"_id"] forKey:@"itemId"];
    [self.navigationController pushViewController:controller animated:YES];
    
    [self performSelector:@selector(delayToSelectMaintenance:) withObject:_dict afterDelay:0.5];
}

- (void) delayToSelectMaintenance:(NSMutableDictionary*)_dict {
    //get the last controller
    MaintenanceDetailedViewController *controller = [[self.navigationController viewControllers] lastObject];
    controller.itemType = itemType;
    NSMutableDictionary *tmpDict = [controller.itemDetailDict mutableCopy];
    [tmpDict setObject:[_dict objectForKey:@"itemType"] forKey:@"maintenanceTypeId"];
    [controller confirmMaintenanceType:_dict itemDetailedDict:tmpDict];
}

#pragma mark UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
    [self setButtonFilterEnable:NO];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
    if (itemType == Building_Type) {
        [self listRoom];
    }
    else {
        [self listEquipment];
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    //create a view to prevent touch when init data
    btnCurtain = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCurtain.frame = CGRectMake(0, 0, 1024, 768);
    [btnCurtain setBackgroundColor:[UIColor whiteColor]];
    btnCurtain.alpha = 0.5;
    [btnCurtain addTarget:self action:@selector(doNothing) forControlEvents:UIControlEventTouchUpInside];
    [ApplicationDelegate.tabBarController.view addSubview:btnCurtain];
    
    if ([mainArray count] > 0) {
        originalArray = [mainArray mutableCopy];
        searchArray = [originalArray mutableCopy];
    }
    else {
        searchArray = [originalArray mutableCopy];
    }
    
    if (itemType == Building_Type) {
        [self listRoomByKey:searchBar.text];
    }
    else {
        [self listEquipmentByKey:searchBar.text];
    }
    
    //kiem tra neu sau khi search ma` ket qua = null thi` tiep tuc tim trong mang? hien tai nhung~ phan` tu co chua' chuoi~ can` search
    if ([mainArray count] == 0) {
        NSMutableIndexSet *indexSets = [NSMutableIndexSet indexSet];
        for (int i=0;i < [searchArray count];i++) {
            NSMutableDictionary *dict = [searchArray objectAtIndex:i];
            NSString *itemName = [dict objectForKey:@"item_name"];
            if ([itemName rangeOfString:searchBar.text].location == NSNotFound) {
                [indexSets addIndex:i];
            }
        }
        [searchArray removeObjectsAtIndexes:indexSets];
        [_mainTableView reloadData];
    }
    
    [searchBar resignFirstResponder];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    if (searchBar.text == Nil || [searchBar.text isEqualToString:@""]) {
        isSearching = NO;
        if (itemType == Building_Type) {
            [self listRoom];
        }
        else {
            [self listEquipment];
        }
        
        [self setButtonFilterEnable:YES];
    }
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
        
        if(!isLoadMore)
        {
            [self.mainTableView hideLoadingMore];
            return;
        }
//        [self.mainTableView showActivity];

        if (itemType == Building_Type) {
            if (!isSearching)
                [self listMoreRoom];
            else
                [self listMoreRoomByKey:_mySearchBar.text];
        }
        else {
            if (!isSearching)
                [self listMoreEquipment];
            else
                [self listMoreEquipmentByKey:_mySearchBar.text];
        }
    }
}

- (void) dealloc {
    NSLog(@"%@ dealloc",self);
//    [self.mySearchBar resignFirstResponder];
//    self.mySearchBar.delegate = nil;
}

@end
